package com.wanmait.demo.filter;


import com.wanmait.demo.pojo.Userinfo;
import com.wanmait.demo.service.UserService;
import com.wanmait.demo.util.CookieUtils;
import com.wanmait.demo.util.EncryptUtils;


import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

//自动登录
@WebFilter("/user/*")
public class UserAutoLoginFilter implements Filter {

    @Resource
    private UserService userService;

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        HttpSession session = request.getSession();
        Userinfo userinfo = (Userinfo) session.getAttribute("loginUser");
        //System.out.println("Userinfo"+""+userinfo);
        if (userinfo == null) {


            String username = CookieUtils.read("username", request);
            //System.out.println("username"+""+username);
            if (username != null) {

                username = EncryptUtils.decrypt(username,3);
                //System.out.println("过滤器姓名"+""+username);
                String password =EncryptUtils.decrypt(CookieUtils.read("password",request),3) ;
               // System.out.println("过滤器密码"+""+password);

                Userinfo userinfo1=new Userinfo();
                userinfo1.setUserName(username);
                userinfo1.setUserPass(password);
                Userinfo userinfo2 =userService.findUser(userinfo1);
                if (userinfo2 != null) {
                    session.setAttribute("loginUser", userinfo2);
                    //写cookie
                    CookieUtils.write("username", EncryptUtils.encrypt(userinfo2.getUserName(),3), "/", 60 * 60 * 24 * 7, response);
                    CookieUtils.write("password",EncryptUtils.encrypt(userinfo2.getUserPass(),3), "/", 60 * 60 * 24 * 7, response);

                }
            }
        }
        chain.doFilter(req, resp);
    }

}
